package main_test

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
)

func readLines(path string) ([]string, error) {
	f, err := os.OpenFile(path, os.O_RDONLY, 0644)
	if err != nil {
		return nil, fmt.Errorf("无法打开文件：%v", err)
	}
	defer f.Close()

	bufio := bufio.NewReader(f)
	lines := make([]string, 0)

	for {
		line, _, err := bufio.ReadLine()
		if err == io.EOF { // 已读完文件
			break
		}

		trimmedLine := strings.TrimRight(string(line), "\r\n")
		if trimmedLine != "" {
			lines = append(lines, trimmedLine)
		}
	}

	return lines, nil
}

type ChatMessageData struct {
	Id               string `json:"id"`
	Role             string `json:"role"`
	Type             string `json:"type"`
	BotId            string `json:"bot_id"`
	ChatId           string `json:"chat_id"`
	Content          string `json:"content"`
	ReasoningContent string `json:"reasoning_content"`
	Usage            Usage  `json:"usage"`
}

type Usage struct {
	TokenCount  uint64 `json:"token_count"`
	OutputCount uint64 `json:"output_count"`
	InputCount  uint64 `json:"input_count"`
}

type chatMessage struct {
	TokenCount   uint64 `json:"token_count"`
	OutputCount  uint64 `json:"output_count"`
	InputCount   uint64 `json:"input_count"`
	ReplyContent string `json:"reply_content"`
}

func Main7() {
	filename := "sse.txt"
	lines, err := readLines(filename)
	if err != nil {
		fmt.Printf("读取文件失败：%v\n", err)
		return
	}
	var lastMessage ChatMessageData
	deltaOk := false
	completedOk := false
	chatMessage := ""

	for _, line := range lines {
		line = strings.TrimSpace(line)
		if !deltaOk {
			if line == "event:conversation.message.delta" {
				deltaOk = true
				completedOk = false
				continue
			}
		}
		if !completedOk {
			if line == "event:conversation.message.completed" {
				completedOk = true
				continue
			}
		}
		if deltaOk && completedOk {
			// fmt.Println(line)
			if line == "event:done" {
				break
			}
			var result ChatMessageData
			// 处理每一行数据，这里只是简单打印出来
			line = strings.Replace(line, "data:", "", -1)
			_ = json.Unmarshal([]byte(line), &result)
			if chatMessage == "" {
				chatMessage = result.Content
			}
			lastMessage = result
		}
	}
	fmt.Println(chatMessage, lastMessage)
}

// 执行：
// go run main.go myfile.txt
